import React, { useState, useContext, useEffect } from "react";
import axios from "axios";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { AppState } from "../App";
import { ethers } from "ethers";
import "../css/blockdetails.css";
import "../css/loader.css";

const BlockDetails = ({ address }) => {
  const App = useContext(AppState);
  const navigate = useNavigate();
  const [transactionData, setTransactionData] = useState(null);
  const [error, setError] = useState(null);
  const [timestamp, setTimestamp] = useState(null);
  const [decodedInput, setDecodedInput] = useState(null);
  const [proposal, setProposal] = useState(null);
  const [userproposal, setUserProposal] = useState(null);
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const hash = searchParams.get("hash");

  const apiKey = "3KB3FGVCMBA1TCY1P9KWHC61SEAZECGI3T";

  const BackToProfile = () => {
    navigate("/header/profile");
  };

  const formatDate = (timestamp) => {
    const date = new Date(timestamp * 1000);
    return date.toLocaleString();
  };

  useEffect(() => {
    const fetchTransactionData = async () => {
      try {
        const network = "sepolia";
        const url = `https://api-${network}.etherscan.io/api?module=account&action=txlist&address=${address}&startblock=0&endblock=99999999&sort=asc&apikey=${apiKey}`;
        const response = await axios.get(url);
        const transactions = response.data.result;
        const transaction = transactions.find((tx) => tx.hash === hash);
        if (transaction) {
          setTransactionData(transaction);
          const blockUrl = `https://api-${network}.etherscan.io/api?module=block&action=getblockreward&blockno=${transaction.blockNumber}&apikey=${apiKey}`;
          const blockResponse = await axios.get(blockUrl);
          const blockData = blockResponse.data.result;
          setTimestamp(blockData.timeStamp);
          decodeInputData(transaction.input);
        }
      } catch (error) {
        setError(error);
      }
    };

    if (hash) {
      fetchTransactionData();
    }
  }, [hash, apiKey, address]);

  const decodeInputData = (inputData) => {
    const iface = new ethers.utils.Interface(
      App.Foundationcontract.interface.fragments
    );

    try {
      const decodedParams = iface.parseTransaction({ data: inputData });
      console.log("解码结果:", decodedParams);
      setDecodedInput(decodedParams);
    } catch (e) {
      console.error("解码失败", e);
    }
  };

  useEffect(() => {
    const getProposal = async () => {
      if (decodedInput && decodedInput.name === "voteRequest") {
        const requestIdHex = decodedInput.args._requestid._hex;
        const requestIdDecimal = parseInt(requestIdHex, 16);
        console.log("proposalId:", requestIdDecimal);
        const proposalInfo = await App.Foundationcontract.requestions(
          requestIdDecimal
        );
        console.log(proposalInfo);
        setProposal(proposalInfo);
      }
    };

    getProposal();
  }, [decodedInput]);

  useEffect(() => {
    const getProposal = async () => {
      if (decodedInput && decodedInput.name === "usersendMoney") {
        const requestIdHex = decodedInput.args._requestid._hex;
        const requestIdDecimal = parseInt(requestIdHex, 16);
        console.log("proposalId:", requestIdDecimal);
        const proposalInfo = await App.Foundationcontract.userrequestions(
          requestIdDecimal
        );
        console.log(proposalInfo);
        setUserProposal(proposalInfo);
      }
    };

    getProposal();
  }, [decodedInput]);

  useEffect(() => {
    const getProposal = async () => {
      if (decodedInput && decodedInput.name === "executeRequest") {
        const requestIdHex = decodedInput.args._requestid._hex;
        const requestIdDecimal = parseInt(requestIdHex, 16);
        console.log("proposalId:", requestIdDecimal);
        const proposalInfo = await App.Foundationcontract.requestions(
          requestIdDecimal
        );
        console.log(proposalInfo);
        setProposal(proposalInfo);
      }
    };

    getProposal();
  }, [decodedInput]);

  if (error) return <div>错误: {error.message}</div>;
  if (!transactionData) return <div>未找到交易</div>;

  return (
    <div className="block-transaction-details">
      <h2>以太坊交易详情</h2>
      <div className="block-transaction-info">
        <p>
          <span className="block-label">交易哈希:</span> {transactionData.hash}
        </p>
        <p>
          <span className="block-label">您的地址:</span> {transactionData.from}
        </p>
        <p>
          <span className="block-label">接收方地址:</span> {transactionData.to}
        </p>
        <p>
          <span className="block-label">交易金额:</span> {transactionData.value}{" "}
          Wei
        </p>
        <p>
          <span className="block-label">交易费用:</span>{" "}
          {(parseInt(transactionData.gasUsed, 10) *
            parseInt(transactionData.gasPrice, 10)) /
            10 ** 18}{" "}
          ETH
        </p>
        <p>
          <span className="block-label">交易状态:</span>{" "}
          {transactionData.txreceipt_status === "1" ? "成功" : "失败"}
        </p>
        <p>
          <span className="block-label">区块高度:</span>{" "}
          {parseInt(transactionData.blockNumber, 10)}
        </p>
        <p>
          <span className="block-label">交易时间:</span>{" "}
          {timestamp ? formatDate(timestamp) : "加载中..."}
        </p>
        <p>
          <span className="block-label">累计 Gas 使用:</span>{" "}
          {parseInt(transactionData.cumulativeGasUsed, 10)}
        </p>
        <p>
          <span className="block-label">Gas 价格:</span>{" "}
          {parseInt(transactionData.gasPrice, 10) / 10 ** 9} Gwei
        </p>
        <p>
          <span className="block-label">确认数:</span>{" "}
          {parseInt(transactionData.confirmations, 10)}
        </p>
        <p>
          <span className="block-label">区块哈希:</span>{" "}
          {transactionData.blockHash}
        </p>
      </div>
      {decodedInput && (
        <div>
          <h3>解码结果</h3>
          <div>
            {/* 投票 */}
            {decodedInput.name === "voteRequest" && (
              <div>
                {proposal && (
                  <div className="block-item-container" key={proposal.tittle}>
                    <div>
                      <p>你已给这个项目投票</p>
                      <button
                        type="button"
                        className="block-btn"
                        onClick={BackToProfile}
                        style={{ marginLeft: "18%" }}
                      >
                        返回页面
                      </button>
                    </div>
                    <div className="block-left-content">
                      <div className="block-left_img">
                        <Link
                          to={`/header/songwarm/${proposal.uniqueid}`}
                          className="block-image-link"
                        >
                          <img
                            src={
                              proposal.photo.length > 0
                                ? `https://blush-chemical-hedgehog-894.mypinata.cloud/ipfs/${
                                    proposal.photo.split(",")[0]
                                  }`
                                : "/images/love.jpg"
                            }
                            style={{ width: 99.9, height: 79.9 }}
                          />
                        </Link>
                      </div>
                      <div className="block-left_right">
                        <div className="block-description">
                          <p>{proposal.description}</p>
                        </div>
                        <div className="block-category">
                          <p>
                            {proposal.tittle}--
                            {ethers.utils.formatUnits(
                              proposal.targetMoney,
                              "wei"
                            )}{" "}
                            爱心币(所需金额)
                          </p>
                          <p>剩余时间--{proposal.endTime.toString()}</p>
                        </div>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            )}
            {/* 首页捐款 */}
            {decodedInput.name === "sendMoney" && (
              <div>
                <div>
                  <p>
                    你已给这个基金会捐款
                    {transactionData.value} Wei
                  </p>
                  <button
                    type="button"
                    className="block-btn"
                    onClick={BackToProfile}
                  >
                    返回页面
                  </button>
                </div>
                <p>
                  <span className="block-label"></span>
                </p>
              </div>
            )}
            {/* 用户创建 */}
            {decodedInput.name === "createUserRequest" && (
              <div
                className="block-item-container"
                key={decodedInput.args._tittle}
              >
                <div>
                  <p>你成功创建此项目</p>
                  <button
                    type="button"
                    className="block-btn"
                    onClick={BackToProfile}
                    style={{ marginLeft: "18%" }}
                  >
                    返回页面
                  </button>
                </div>

                <div className="block-left-content">
                  <div className="block-left_img">
                    <img
                      src={
                        decodedInput.args._photo
                          ? `https://blush-chemical-hedgehog-894.mypinata.cloud/ipfs/${decodedInput.args._photo}`
                          : "/images/love.jpg"
                      }
                    />
                  </div>
                  <div className="block-left_right">
                    <div className="block-description">
                      <p>{decodedInput.args._description}</p>
                    </div>
                    <div className="block-category">
                      <p>
                        {decodedInput.args._tittle}--
                        {ethers.utils.formatUnits(
                          decodedInput.args._targetMoney,
                          "wei"
                        )}{" "}
                        爱心币(所需金额)
                      </p>
                      <p>剩余时间--{decodedInput.args._endTime.toString()}</p>
                    </div>
                  </div>
                </div>
              </div>
            )}
            {/* 管理员创建 */}
            {decodedInput.name === "createAdminRequest" && (
              <div
                className="block-item-container"
                key={decodedInput.args._tittle}
              >
                <div>
                  <p>你成功创建此项目</p>
                  <button
                    type="button"
                    className="block-btn"
                    onClick={BackToProfile}
                    style={{ marginLeft: "18%" }}
                  >
                    返回页面
                  </button>
                </div>
                <div className="block-left-content">
                  <div className="block-left_img">
                    <img
                      src={
                        decodedInput.args._photo
                          ? `https://blush-chemical-hedgehog-894.mypinata.cloud/ipfs/${
                              decodedInput.args._photo.split(",")[0]
                            }`
                          : "/images/love.jpg"
                      }
                    />
                  </div>
                  <div className="block-left_right">
                    <div className="block-description">
                      <p>{decodedInput.args._description}</p>
                    </div>
                    <div className="block-category">
                      <p>
                        {decodedInput.args._tittle}--
                        {ethers.utils.formatUnits(
                          decodedInput.args._targetMoney,
                          "wei"
                        )}{" "}
                        爱心币(所需金额)
                      </p>
                      <p>剩余时间--{decodedInput.args._endTime.toString()}</p>
                    </div>
                  </div>
                </div>
              </div>
            )}
            {/* 用户项目捐款 */}
            {decodedInput.name === "usersendMoney" && (
              <div>
                {userproposal && (
                  <div
                    className="block-item-container"
                    key={userproposal.tittle}
                  >
                    <div>
                      <p>你已给这个项目捐钱</p>
                      <button
                        type="button"
                        className="block-btn"
                        onClick={BackToProfile}
                        style={{ marginLeft: "18%" }}
                      >
                        返回页面
                      </button>
                    </div>
                    <div className="block-left-content">
                      <div className="block-left_img">
                        <Link
                          to={`/header/forus/${userproposal.uniqueid}`}
                          className="block-image-link"
                        >
                          <img
                            src={
                              userproposal.photo
                                ? `https://blush-chemical-hedgehog-894.mypinata.cloud/ipfs/${userproposal.photo}`
                                : "/images/love.jpg"
                            }
                          />
                        </Link>
                      </div>
                      <div className="block-left_right">
                        <div className="block-description">
                          <p>{userproposal.description}</p>
                        </div>
                        <div className="block-category">
                          <p>
                            {userproposal.tittle}--
                            {ethers.utils.formatUnits(
                              userproposal.targetMoney,
                              "wei"
                            )}{" "}
                            爱心币(所需金额)
                          </p>
                          <p>剩余时间--{userproposal.endTime.toString()}</p>
                        </div>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            )}
            {/* 拨款 */}
            {decodedInput.name === "executeRequest" && (
              <div>
                {proposal && (
                  <div className="block-item-container" key={proposal.tittle}>
                    <div style={{ marginLeft: "4%" }}>
                      <p>
                        <span className="block-label"></span>你已给这个项目拨款
                        <button
                          type="button"
                          className="block-btn"
                          onClick={BackToProfile}
                          style={{ marginLeft: "11%", marginTop: "4%" }}
                        >
                          返回页面
                        </button>
                      </p>
                    </div>
                    <div
                      className="block-left-content"
                      style={{ marginLeft: "6%" }}
                    >
                      <div className="block-left_img">
                        <Link
                          to={`/header/songwarm/${proposal.uniqueid}`}
                          className="block-image-link"
                        >
                          <img
                            src={
                              proposal.photo
                                ? `https://blush-chemical-hedgehog-894.mypinata.cloud/ipfs/${
                                    proposal.photo.split(",")[0]
                                  }`
                                : "/images/love.jpg"
                            }
                          />
                        </Link>
                      </div>
                      <div className="block-left_right">
                        <div className="block-description">
                          <p>{proposal.description}</p>
                        </div>
                        <div className="block-category">
                          <p>
                            {proposal.tittle}--
                            {ethers.utils.formatUnits(
                              proposal.targetMoney,
                              "wei"
                            )}{" "}
                            爱心币(所需金额)
                          </p>
                          <p>剩余时间--{proposal.endTime.toString()}</p>
                        </div>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

export default BlockDetails;
